package com.crl.ui.controls.pages
{
	import com.crl.core.IDataRenderer;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	public class Page extends EventDispatcher implements IPageable ,IDataRenderer
	{
		protected var _data:Array;
		protected var _currentPageData:Array;
		protected var _length:uint;
		
		protected var _pageCount:int;
		protected var _currentPage:int;
		protected var _totalPage:int;
		
		private var ticker:Timer;
		public function Page(pageCount:uint=5)
		{
			_currentPage = 0;
			_totalPage = 0;
			
			_currentPageData=[];
			this._pageCount = pageCount;
			
			ticker=new Timer(20,1);
			ticker.addEventListener(TimerEvent.TIMER_COMPLETE,_doUpdate);
		}
		
		public function previousPage():void
		{
			this.currentPage=(_currentPage-1);
		}
		
		public function nextPage():void
		{
			this.currentPage=(_currentPage+1);
		}
		
		public function get pageCount():uint
		{
			return _pageCount;
		}
		
		public function set pageCount(value:uint):void
		{
			_pageCount=value;
			this.update();
		}
		
		public function size():uint
		{
			return _length;
		}
		
		public function get currentPageData():Array{
			return _currentPageData;
		}
		
		public function set currentPage(value:uint):void
		{
			value=Math.min(Math.max(0,value),_totalPage)
			_currentPage=value;
			this.update();
		}
		
		public function get currentPage():uint
		{
			return _currentPage;
		}
		
		public function get totalPage():uint
		{
			return _totalPage;
		}
		
		public function get hasNextPage():Boolean
		{
			return this._currentPage<this._totalPage;
		}
		
		public function get hasPreviousPage():Boolean
		{
			return this._currentPage>0 ;
		}
		
		
		public function get data():*{
			return _data
		}
		public function set data(value:*):void{
			if(value is Array ==false){
				throw new Error("分页数据必须提供为数组");
			}
			this._data=value as Array;
			_length=_data.length;
			
			this.update();
		}
		
		private function update():void{
			ticker.reset();
			ticker.start();
		}
		protected function _doUpdate(event:Event=null):void{
			_currentPageData.splice(0);
			
			this._totalPage=Math.ceil(_length/_pageCount)-1;
			
			if(_totalPage<0){
				this.dispatchEvent(new Event(Event.CHANGE));
				return;
			}
			
			if(_currentPage>_totalPage){
				_currentPage=0;
			}
			
			var _current:uint
			var _last:uint;
			
			_current=_currentPage*pageCount;
			if(_currentPage==_totalPage){
				_last=_length;
			}else{
				_last=_current+_pageCount;
			}
			
			for(var i:uint = _current ; i < _last ; i++){
				_currentPageData.push(_data[i]);
			}
			
			this.dispatchEvent(new Event(Event.CHANGE));
		}
	}
}